﻿using System;
using System.Collections.Generic;
using Algoritmia.DataStructures.Maps;

namespace Demos.DataStructures
{
    public delegate void CambioHandler(int hash, KeyValuePair<string, Demos.Hashmap.Palabra> claveValor);

    [Serializable]
    class ObservableHashMap : HashMap<string, Hashmap.Palabra>
    {
        public event CambioHandler Cambio;

        public Hashmap.Palabra this[string key]
        {
            get
            {
                var hash = Math.Abs(key.GetHashCode() % _capacity);
                if (_supportList[hash] != null)
                {
                    foreach (var ekv in _supportList[hash])
                    {
                        if (ekv.Key.Equals(key))
                        {
                            return ekv.Value;
                        }
                    }
                }
                throw new KeyNotFoundException(String.Format("Key {0} is not contained", key));
            }
            set
            {
                var nuevo = new KeyValuePair<string, Hashmap.Palabra>(key, value);
                var hash = Math.Abs(key.GetHashCode() % _capacity);
                if (_supportList[hash] == null)
                    _supportList[hash] = base._createContainedLists();

                for (var i = 0; i < _supportList[hash].Count; i++)
                {
                    if (_supportList[hash][i].Key.Equals(key))
                    {
                        _supportList[hash].RemoveAt(i);
                        _supportList[hash].Add(nuevo);
                        return;
                    }
                }
                var par = new KeyValuePair<string, Hashmap.Palabra>(key, value);
                _supportList[hash].Add(par);
                _count++;
                Cambio(hash, nuevo);
            }
        }
    }
}